const app = getApp()

Page({
  data: {
    isAdmin: false,
    latestProducts: [],
    banners: []
  },

  onLoad: function() {
    this.checkUserRole()
    this.getLatestProducts()
  },

  // 检查用户角色
  async checkUserRole() {
    try {
      const db = wx.cloud.database()
      const { data } = await db.collection('users').where({
        _openid: app.globalData.openid
      }).get()
      
      this.setData({
        isAdmin: data[0]?.role === 'admin'
      })

      // 如果是管理员，显示管理入口
      if (this.data.isAdmin) {
        wx.showTabBarRedDot({
          index: 2
        })
      }
    } catch (error) {
      console.error('检查用户角色失败：', error)
    }
  },

  // 获取最新商品
  async getLatestProducts() {
    try {
      const db = wx.cloud.database()
      const { data } = await db.collection('products')
        .where({
          status: 'on'
        })
        .orderBy('createTime', 'desc')
        .limit(10)
        .get()
      
      this.setData({
        latestProducts: data
      })
    } catch (error) {
      console.error('获取最新商品失败：', error)
    }
  }
}) 